package com.ceuer.demo.sync;

/*
不安全的线程问题
 */
public class SafeBank {
	public static void main(String[] args) {
		Account1 account=new Account1(1000, "结婚基金");
		
		Drawing1 you=new Drawing1(account, 50, "你");
		Drawing1 wife=new Drawing1(account, 100, "你的妻子");
		
		you.start();
		wife.start();
		
	}
}

/**
 * 账户
 */
class Account1{
	int money;//余额
	String name;//卡名
	
	public Account1(int money, String name) {
		this.money = money;
		this.name = name;
	}
}

/**
 * 银行:模拟取款
 */
class Drawing1 extends Thread{
	Account1 account;//账户
	int drawingMoney;//去了多少钱
	int nowMoney;//现在手里有多少钱
	
	public Drawing1(Account1 account, int drawingMoney, String name) {
		super(name);
		this.account = account;
		this.drawingMoney = drawingMoney;
	}
	
	//synchronized 默认锁的是this， 此处在方法上添加synchronized不能同步锁，因为这里的代码不能确定是否只有账户在操作
	//改变的对象是account，所以只要同步accout这个账户就可以，所以使用synchronized代码块来
	//synchronized(account){}
	@Override
	public void run() {
		//锁的对象是变化的量，需要增删改的对象
		synchronized (account){
			//判断有没有钱
			if(account.money- drawingMoney <0){
				System.out.println(Thread.currentThread().getName()+"钱不够，取不了！");
				return;
			}
			//模拟延迟
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			//卡内余额=余额-你取的钱
			account.money=account.money - drawingMoney;
			//你手里的钱
			nowMoney=nowMoney + drawingMoney;
			
			System.out.println(account.name+"余额："+account.money);
			
			System.out.println(this.getName()+"手里的钱："+nowMoney);
		}
	}
}